package com.oa.web.action;

import com.oa.bean.User;
import com.oa.service.UserService;
import com.oa.web.action.base.BaseAction;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.util.List;

@Controller
@Scope("prototype")
public class UserAction extends BaseAction<User> {

    @Autowired
    private UserService userService;

    // 属性驱动 获取验证码
    private String checkcode;

    // 退出登录的方法
    public String logOut() {
        session.clear();
        return LOGOUT;
    }

    // 登录方法
    public String login() {
        // 获取Session中的值
        String key = (String) session.get("key");
        // 验证验证码是否正确
        if (StringUtils.isNotBlank(checkcode) && checkcode.equals(key)) {
            User user = userService.login(model);
            if (user != null) {
                // 登陆成功 将User保存到Session中跳转到首页
                session.put("userInfo", user);
                this.writeText("success");
                return NONE;
            } else {
                // 跳转到登陆页面
                // 添加错误信息
                session.put("userInfo", null);
//                this.addActionError("用户名或密码输入错误");
                this.writeText("failed");
                return NONE;
            }
        } else {
//            this.addActionError("验证码错误");
            return NONE;
        }
    }

    public String validataUsername() {
        Integer i = userService.validataUsername(model.getUsername());
        this.writeText(i + "");
        return NONE;
    }

    public String validataCheckCode() {
        // 获取Session中的值
        String key = (String) session.get("key");
        // 验证验证码是否正确
        if (StringUtils.isNotBlank(checkcode) && checkcode.equals(key)) {
            this.writeText("1");
        } else {
            this.writeText("0");
        }
        return NONE;
    }

    public void setCheckcode(String checkcode) {
        this.checkcode = checkcode;
    }
}
